package club.babyf.nativeai.demo.algorithm;

/**
 * _25_AddListNode.
 *
 * @author zhanglei.
 * @date 2025/7/26 08:39.
 * @description 链表相加.
 */
public class _25_AddListNode {

    public static ListNode addListNode(ListNode l1, ListNode l2) {
        int carry = 0;
        ListNode dummy = new ListNode(0);
        ListNode l3 = dummy;
        while (l1 != null || l2 != null || carry != 0) {
            if (l1 != null) {
                carry += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                carry += l2.val;
                l2 = l2.next;
            }
            l3.next = new ListNode(carry % 10);
            l3 = l3.next;
            carry /= 10;
        }
        return dummy.next;
    }

    public static class ListNode {

        int val;

        ListNode next;

        public ListNode(int val) {
            this.val = val;
        }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            ListNode current = this;
            while (current != null) {
                sb.append(current.val);
                ListNode next = current.next;
                if (next != null) {
                    sb.append(" -> ");
                }
                current = next;
            }
            return sb.toString();
        }

    }

    public static void main(String[] args) {
        ListNode head1 = new ListNode(1, new ListNode(2, new ListNode(3)));
        System.out.println(head1);
        ListNode head2 = new ListNode(5, new ListNode(9, new ListNode(5)));
        System.out.println(head2);
        ListNode listNode = addListNode(head1, head2);
        System.out.println(listNode);
    }

}
